$(document).ready(function() {

    var VAL ={
        NORMAL : "0000000"  ,
        EVT_USER : $("#userId").text(),
        T_MTPPMITEM : 'MTPPMITEM',
        T_MTPTOOLPM : 'MTPTOOLPM',
        T_FBPBISTOL : "FBPBISTOL",
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };

    var domObj = {
        W : $(window),

        $pmEvtSeqId    : $("#pmEvtSeqId"),
        $toolIdSel     : $("#toolIdSel"),
        $pvPmTime      : $("#pvPmTime"),
        $nxPvTime      : $("#nxPvTime"),
        $pmStat        : $("#pmStat"),
        $pmChStatTime  : $("#pmChStatTime"),
        $pmNoSel       : $("#pmNoSel"),

        buttons : {
            $save_btn : $("#save_btn")
        },

        grids:{
            $pmMtrlListDiv : $("#pmMtrlListDiv"),
            $pmMtrlListGrd : $("#pmMtrlListGrd"),
            $pmMtrlListPg  : $("#pmMtrlListPg")
        }
    };

    var controlsFunc={
        iniPmInfoFunc : function(){//初始化页面信息
           var evtSeqId =  $.query.get("evt_seq_id");
           var toolId   =  $.query.get("tool_id");
           var pmNo     =  $.query.get("pm_NO");
           var iary     =  {
               tool_id :toolId
           }
            var inTrxObj = {
                trx_id     : VAL.T_FBPBISTOL ,
                action_flg : 'O',
                iary       :[iary]
            };
            var outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if( outTrxObj.rtn_code == VAL.NORMAL ) {
                domObj.$pmEvtSeqId.text(evtSeqId);
                domObj.$pmNoSel.text(pmNo);
                domObj.$toolIdSel.text(toolId);
                domObj.$pvPmTime.text(outTrxObj.pv_pm_date);
                domObj.$nxPvTime.text(outTrxObj.nx_pm_date);
                domObj.$pmStat.text(outTrxObj.tool_stat);
                domObj.$pmChStatTime.text(outTrxObj.evt_timestamp);
            }

            //查询PM信息是否需要工艺和生产
            var inTrx = {
                trx_id     : VAL.T_MTPTOOLPM,
                action_flg : 'E',
                evt_seq_id : evtSeqId
            }
            var outTrx = comTrxSubSendPostJson(inTrx);
            if(outTrx.rtn_code == VAL.NORMAL ){
                var tech_confirm_flg = outTrx.oaryA[0].tech_confirm_flg;
                var prod_confirm_flg = outTrx.oaryA[0].prod_confirm_flg;
                if(tech_confirm_flg == "N"){
                    $("#tech_confirm_per").attr(VAL.DISABLED_ATTR);
                }
                if(prod_confirm_flg == "N"){
                    $("#pro_confirm_per").attr(VAL.DISABLED_ATTR);
                }
            }
        },
        iniPmGridFunc : function(){//初始化页面信息
            var evtSeqId = $.trim(domObj.$pmEvtSeqId.text());
            var inTrxObj = {
                trx_id        : VAL.T_MTPPMITEM ,
                action_flg    : 'M'        ,
                evt_seq_id    : evtSeqId
            };
            var outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if( outTrxObj.rtn_code == _NORMAL ) {
                setGridInfo(outTrxObj.oaryA, "#pmMtrlListGrd");
            }
        },

        //初始化人员配置
        initStaffingSel : function () {
            var warp, option;
            SelectDom.initWithSpace($("#staffing"));
            warp = document.createDocumentFragment();
            for (i = 0; i < 10; i++) {
                option = document.createElement("option");
                option.value = i + 1;
                option.text = i + 1;
                warp.appendChild(option);
            }
            $("#staffing").append(warp);
        }
    };
    var btnFunc = {
        saveFunc : function() {
            var evtSeqId = $.trim(domObj.$pmEvtSeqId.text());
            var len=$("#pmMtrlListGrd").jqGrid('getGridParam','records');
            var ids = domObj.grids.$pmMtrlListGrd.jqGrid('getGridParam', 'selarrrow');
            if(ids.length!=len){
                showErrorDialog("", "请先完成所有保养项目！");
                return false;
            }
            var iaryA =[];
            for (var i = 0; i < ids.length; i++) {
                if ($('#pmMtrlListGrd :text[role="textbox"]').length > 0) {
                    var v = $('#pmMtrlListGrd :text[role="textbox"]').val();
                    $('#pmMtrlListGrd :text[role="textbox"]').parent().attr('title', v);
                    $('#pmMtrlListGrd :text[role="textbox"]').parent().html(v);
                }
                var rowData = domObj.grids.$pmMtrlListGrd.jqGrid("getRowData", ids[i]);
                if (!rowData.data_value) {
                    showErrorDialog("", "第'" + $('#' + ids[i])[0].rowIndex + "'行实际值不能为空");
                    return false;
                }
              /*  if (!ComRegex.isNumber(rowData.data_value)) {
                    showErrorDialog("", "第" + $('#' + ids[i])[0].rowIndex + "行实际值格式不正确！");
                    return false;
                }*/
                //检查是否超出下规格
                if(rowData['l_spec']){
                    if(!ComRegex.isNumber(rowData.data_value)){
                        showErrorDialog("", "第" + $('#' + ids[i])[0].rowIndex + "行数值格式不正确！");
                        return false;
                    }else if(parseFloat(rowData['data_value'],10) < parseFloat(rowData['l_spec'],10)){
                        showErrorDialog("", "第" + $('#' + ids[i])[0].rowIndex + "行数值小于下规格值"+ parseFloat(rowData['l_spec'],10) + "！");
                        return false;
                    }
                }
                //检查是否超出上规格
                if(rowData['u_spec']){
                    if(!ComRegex.isNumber(rowData.data_value)){
                        showErrorDialog("", "第" + $('#' + ids[i])[0].rowIndex + "行数值格式不正确！");
                        return false;
                    }else if(parseFloat(rowData['u_spec'],10) < parseFloat(rowData['data_value'],10)){
                        showErrorDialog("", "第" + $('#' + ids[i])[0].rowIndex + "行数值大于上规格值"+ parseFloat(rowData['u_spec'],10) + "！");
                        return false;
                    }
                }

                //维护人
                if(!rowData.maintenance_man){
                    showErrorDialog("","维护人不能为空！");
                    return false;
                }

                var iary = {
                    data_dsc :   rowData['data_dsc'],
                    l_spec :     rowData['l_spec'],
                    u_spec :     rowData['u_spec'],
                    data_value : rowData['data_value'],
                    maintenance_man : rowData['maintenance_man'],
                    ac_pm_note : rowData['ac_pm_note']
                }
                iaryA.push(iary);
            }

            // var staffing = $("#staffing").val();
            var eqt_confirm_per = $("#eqt_confirm_per").val();
            var pro_confirm_per = $("#pro_confirm_per").val();
            var tech_confirm_per = $("#tech_confirm_per").val();
            var assistants = $("#assistants").val();
            var ac_pm_note = $("#abnormal_note").val();
            // if(!staffing){
            //     showErrorDialog("","人员配置不能为空！");
            //     return false;
            // }
            // if(!eqt_confirm_per){
            //     showErrorDialog("","设备确认人不能为空！");
            //     return false;
            // }
            // if(!pro_confirm_per){
            //     showErrorDialog("","生产确认人不能为空！");
            //     return false;
            // }

            var inObj = {
                trx_id : VAL.T_MTPTOOLPM,
                action_flg : "S",
                evt_usr : VAL.EVT_USER,
                evt_seq_id    : evtSeqId,
                iaryA  : iaryA,
                assistants : assistants,
                eqt_confirm_per : eqt_confirm_per,
                pro_confirm_per : pro_confirm_per,
                tech_confirm_per : tech_confirm_per,
                ac_pm_note : ac_pm_note
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var length = ids.length;
                for(var i=0;i<length;i++) {
                    domObj.grids.$pmMtrlListGrd.jqGrid("delRowData",ids[0]);
                }
                showSuccessDialog("保存成功");
            }
        }
    };

    function iniGridInfo() {
        var ItemListInfoCM = [
            {name: 'data_dsc'        , index: 'data_dsc'    ,    label: "保养项目名称"     ,width: 300 },
            {name: 'u_spec'          , index: 'u_spec'      ,    label: "上规格"           ,width: 150 },
            {name: 'l_spec'          , index: 'l_spec'      ,    label: "下规格"           ,width: 150 },
            {name: 'data_value'      , index: 'data_value'  ,    label: "实际值"           ,width: 150 ,editable : true},
            // {name: 'data_group_fk'   , index: 'data_group_fk'  , label: "零部件更换内容"   ,width: 150 ,editable : true},
            {name: 'maintenance_man'      , index: 'maintenance_man'     , label: "维护人"             ,width: 150 ,editable : true},
            {name: 'ac_pm_note'      , index: 'ac_pm_note'     , label: "备注"             ,width: 150 ,editable : true}
        ];
        domObj.grids.$pmMtrlListGrd.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            autowidth:true,//宽度根据父元素自适应
            height : 400,
            shrinkToFit:false,
            scroll:false,
            resizable : true,
            loadonce:true,
            fixed: true,
            viewrecords : true, //显示总记录数
            pager : '#pmMtrlListPg',
            rownumbers  :true ,//显示行号
            pginput  : false ,
            rownumWidth : 20,  //行号列宽度
            multiselect : true,
            cellEdit:true,
            cellsubmit:"clientArray",
            emptyrecords :true ,
            colModel: ItemListInfoCM
        });
    }
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        controlsFunc.iniPmInfoFunc();
        controlsFunc.iniPmGridFunc();
        // controlsFunc.initStaffingSel();
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$save_btn.click(function(){
            btnFunc.saveFunc();
        });

    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        $("form").submit(function(){
            return false;
        });
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };

    initializationFunc();
});